﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using pos.excption;
using System.Collections;
using Spring.Data.NHibernate.Support;
using Spring.Data.NHibernate;
using NHibernate;
using NHibernate.Criterion;

namespace pos.entity
{
    class ReSettle : IHibernateCallback
    {

        private string commodityID;
         public ReSettle(String id)
         {
             commodityID = id;
         }
         public object DoInHibernate(ISession session)
        {

            t_commodity t = t_commodity.GetByCommodityID(commodityID);
             if(t.packageFlag==t_commodity.YESPACKAGE)
                 t = t_commodity.GetByCommodityID(t.packageCommodityID);
            DetachedCriteria dc= t.DC.Add(Restrictions.Or(
                 Restrictions.Eq("commodityID",t.commodityID),
                 Restrictions.Eq("packageCommodityID",t.commodityID)));
             IList list=t.List(dc);
             string wh="";
         
             foreach(Commodity c in list)
             {
                 if(wh=="")
                    wh+=" commodityID in ("+c.commodityID;
                 else
                     wh+=","+c.commodityID;
             }
             wh+=")";
             

             string[] sqls=new string[]{"insert into t_sale select * from t_hsale where"+wh,
"update t_sale set settleState=0 where"+wh,
"delete from t_hsale where"+wh,
"insert into t_returned  select * from t_hreturned where"+wh,
"delete from t_hreturned where"+wh,
"update t_hstock set saleAmount=0,saleMoney=0,storageAmount=stockAmount,storageMoney=stockMoney,returnedAmount=0,returnedMoney=0,lossMoney=0 where"+wh,
"delete from t_storage where"+wh,
"insert into t_stock select * from t_hstock  where"+wh,
"delete  from t_hstock where"+wh,
"delete from t_salereport where"+wh};
             
            //throw new Exception("test");
            ISQLQuery sqlcmd;
             foreach(string sql in sqls)
             {
                
                 sqlcmd = session.CreateSQLQuery(sql);
                 sqlcmd.ExecuteUpdate();
             }
               // db.ExeSql("insert into t_hsale select * from t_sale where settleState=1 and  saleType=0");
               // db.ExeSql("delete from t_sale where settleState=1 and  saleType=0");
              
           
            return true;
        }


    }
}
